<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="请选择时间">
              <a-date-picker
                placeholder="请选择时间"
                mode="year"
                v-model="queryParam.year"
                :open="dataopen"
                format="YYYY"
                :allowClear="false"
                @openChange="openChangeYear"
                @panelChange="panelChangeYear"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
            </span>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="computePoints" icon="thunderbolt">计算积分</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="statusSlot" slot-scope="text, record">
          <a-tag v-if="text=='是'" color="#87d068">{{text}}</a-tag>
          <a-tag v-else color="#f50">{{text}}</a-tag>
        </template>

        <template slot="fileSlot" slot-scope="record">
          <span v-if="record.uploadStatus==0" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(record.filePath)">
            下载
          </a-button>
        </template>
        <template slot="action" slot-scope="text, record, index">

          <a-upload
            name="file"
            :action="url.uploadUrl"
            :headers="headers"
            :data="{'biz':'classTime/'+record.year, 'year':record.year, 'month':record.month}"
            :showUploadList='false'
            @change="handleChange($event,index)"
            accept="application/vnd.ms-excel,
            application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >
            <a-button size="small" type="primary"> <a-icon type="upload" /> 上传 </a-button>
          </a-upload>
        </template>

      </a-table>
    </div>

  </a-card>
</template>

<script>
import Vue from 'vue'
import { httpAction, getAction, postAction } from '@/api/manage'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import moment from 'moment'
import { ACCESS_TOKEN, CURRENT_DATE } from '@/store/mutation-types'

export default {
  name: 'GfxyTClasstimeUploadList',
  mixins:[JeecgListMixin, mixinDevice],
  data () {
    return {
      description: '课时文件上传管理页面',
      dataopen: false,
      headers:{},
      containerId:'',
      // canLoad:false,
      // 表头
      queryParam:{
        year: ''
      },
      isorter:{
        column: 'month'
      },
      ipagination: {
        pageSize: 12,
        pageSizeOptions: ['12', '24', '36'],
      },
      columns: [
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'时间',
          align:"center",
          dataIndex: 'year'
        },
        {
          title:'月',
          align:"center",
          dataIndex: 'month'
        },
        {
          title:'上传状态',
          align:"center",
          dataIndex: 'uploadStatus_dictText',
          scopedSlots: {customRender: 'statusSlot'}
        },

        {
          title:'加载状态',
          align:"center",
          dataIndex: 'loadStatus_dictText',
          scopedSlots: {customRender: 'statusSlot'}
        },
        {
          title:'下载',
          align:"center",
          scopedSlots: {customRender: 'fileSlot'}
        },
        {
          title:'文件路径',
          align:"center",
          dataIndex: 'filePath'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          fixed:"right",
          width:147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: "/classtime/classtimeUpload/listAndInsert",
        delete: "/classtime/classtimeUpload/delete",
        edit: "/classtime/classtimeUpload/edit",
        deleteBatch: "/classtime/classtimeUpload/deleteBatch",
        exportXlsUrl: "/classtime/classtimeUpload/exportXls",
        importExcelUrl: "/classtime/classtimeUpload/importExcel",
        uploadUrl: window._CONFIG['domianURL']+"/classtime/classtimeUpload/upload",
        computePointsUrl: "/points/classtimeScore/compute",
      },
      dictOptions:{},
      superFieldList:[],
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    // //---------------------------- begin 图片左右换位置 -------------------------------------
    this.headers = {"X-Access-Token":token};
    this.containerId = 'container-ty-'+new Date().getTime();
    this.getSuperFieldList();
    this.queryParam.year = Vue.ls.get(CURRENT_DATE);
    this.searchQuery();
  },
  computed: {
    importExcelUrl: function(){
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },// 点击选择框事件 弹出日期组件选择年
    canLoad(){
      let result = this.dataSource.every((item) => {
        return item.uploadStatus == 1
      });
      return result;

    },
  },
  methods: {
    initDictConfig(){
    },
    getSuperFieldList(){
      let fieldList=[];
      fieldList.push({type:'string',value:'year',text:'时间',dictCode:''})
      fieldList.push({type:'int',value:'month',text:'月',dictCode:''})
      fieldList.push({type:'int',value:'uploadStatus',text:'上传状态',dictCode:'yn_status'})
      fieldList.push({type:'int',value:'loadStatus',text:'加载状态',dictCode:'yn_status'})
      fieldList.push({type:'string',value:'filePath',text:'文件路径',dictCode:''})
      this.superFieldList = fieldList
    },
    handleChange(info,index){
      console.log("handleChange")
      console.log(info)
      this.loading = true;
      if(info.file.status==='done'){
        if(info.file.response.success){

          let file = info.fileList[0].response.message;
          let record = this.dataSource[index];
          record.filePath = file;
          record.uploadStatus = 1;
          record.loadStatus=1;
          this.updateDate(record)
          console.log("computer:" + this.canLoad);

        }

      } else if(info.file.status==='error'){
        this.loading = false;
        this.errorModal('文件上传错误',info.file);
      }
    },
    openChangeYear: function(status) {
      if (status) {
        this.dataopen = true;
      } else {
        this.dataopen = false;
      }
    },
    // 选择年之后 关闭弹框
    panelChangeYear: function(value){
      const endOfYear = moment().endOf('year')
      if(value.endOf('year')>endOfYear){
        // alert("所选时间不能超过当前时间");
        this.errorModal('时间选择错误','所选时间不能超过当前时间');
      } else {
        this.queryParam.year = value.format('YYYY');
      }
      this.dataopen = false;
    },
    disabledDate: function(current){
      const yearStart = moment().subtract(10, 'year')
      const yearEnd = moment().endOf('year')
      return current.endOf('year') < yearStart || current.endOf('year') > yearEnd
    },

    errorModal: function(title, content) {
      this.$error({
        title: title,
        content: content,
      });
    },
    updateDate(record){
      httpAction(this.url.edit ,record,'put').then((res)=>{
        if(res.success){
          this.$message.success(res.message);
          this.loadData(1)
        }else{
          this.$message.warning(res.message);
        }
      }).finally(() => {
        this.loading = false;
      })
    },
    computePoints(){


      this.loading = true;
      postAction(this.url.computePointsUrl, {'year':this.queryParam.year}).then((res)=>{
        if(res.success){
          this.$message.success(res.message);
          this.loadData(1)
        }else{
          this.$message.warning(res.message);
        }
      }).finally(() => {
        this.loading = false;
      })
    },
    loadClasstime(){

    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>